<?php

namespace app\service;

use app\core\Request;
use app\core\Service;
use app\model\Attachment;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Filesystem;
use think\file\UploadedFile;
use app\model\ZtcUser;
use app\core\util\http;
use app\core\exception\BusinessException;

/**
 * 附件服务
 * @extends Service<AttachmentService>
 */
class AttachmentService extends Service
{

    /**
     * 单文件上传
     * @param UploadedFile $file
     * @param int $parent_id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function upload(UploadedFile $file, int $parent_id = 0)
    {
        // check file todo
        // 父级目录
        $parent_path = '';
        // 上传到本地服务器
        if ($parent_id > 0) {
            $parent_attchment = Attachment::where("attachment_type", 1)->find($parent_id);
            if ($parent_attchment) {
                $parent_path = ltrim($parent_attchment['path'], "/");
            }
        }

        $file_mime = $file->getMime();
        $saveData = [
            'parent_id' => $parent_id,
            'attachment_type' => 2,
            'file_type' => explode("/", $file_mime)[1] ?? 'file',
            'file_name' => $file->getOriginalName(),
            'file_size' => $file->getSize(),
            'mimetype' => $file_mime,
            'disk' => env('filesystem.public', 'public'),
            'sha1' => $file->sha1(),
        ];

        $attachment = Attachment::where('sha1', $saveData['sha1'])->find();
        if (!$attachment){
            $path = $this->putFile($parent_path, $file);
            $saveData['path'] = $path;
            $attachment = Attachment::create($saveData);
        }else{
            // 判断文件是否存在
            if (!file_exists(app()->getRootPath() . 'public' . $attachment['path'])){
                $attachment->delete();
                // 重新上传
                $path = $this->putFile($parent_path, $file);
                $saveData['path'] = $path;
                $attachment = Attachment::create($saveData);
            }
            $path = $attachment['path'];
        }

        return $attachment;
    }
    public function uploadfile(UploadedFile $file, int $parent_id = 0)
    {

        // check file todo
        // 父级目录
        $parent_path = '';
        // 上传到本地服务器
        if ($parent_id > 0) {
            $parent_attchment = Attachment::where("attachment_type", 1)->find($parent_id);
            if ($parent_attchment) {
                $parent_path = ltrim($parent_attchment['path'], "/");
            }
        }

        $file_mime = $file->getMime();
        $saveData = [
            'parent_id' => $parent_id,
            'attachment_type' => 2,
            'file_type' => explode("/", $file_mime)[1] ?? 'file',
            'file_name' => $file->getOriginalName(),
            'file_size' => $file->getSize(),
            'mimetype' => $file_mime,
            'disk' => env('filesystem.public', 'public'),
            'sha1' => $file->sha1(),
        ];

        $attachment = Attachment::where('sha1', $saveData['sha1'])->find();
        if (!$attachment){
            $path = $this->putFile($parent_path, $file);
            $saveData['path'] = $path;
            $attachment = Attachment::create($saveData);
        }else{
            // 判断文件是否存在
            if (!file_exists(app()->getRootPath() . 'public' . $attachment['path'])){
                $attachment->delete();
                // 重新上传
                $path = $this->putFile($parent_path, $file);
                $saveData['path'] = $path;
                $attachment = Attachment::create($saveData);
            }
            $path = $attachment['path'];
        }

//        $username = ZtcUser::where('user_id', $user_id)->value('username');
//
//        if (empty($username)) {
//            throw new BusinessException('请先绑定直通车账号');
//        }
//
//        $Http_util = Http::invoke();
//        $res = $Http_util->request("POST", "http://127.0.0.1:8100/uploadify_visit", [
//            'headers' => ['Content-Type' => 'application/json'],
//            'body' => json_encode([
//                'username' => $username,
//                'imgPath' => '..'.str_replace("\\","/",$attachment['path']),
//            ])
//        ]);
//        $res = json_decode($res, 256);
//        if ($res['code'] != 1) {
//
//            throw new \Exception($res['msg']);
//        }
        return $attachment;
    }

    public function uploadidf(UploadedFile $file, int $parent_id = 0,$user_id='')
    {

        // check file todo
        // 父级目录
        $parent_path = '';
        // 上传到本地服务器
        if ($parent_id > 0) {
            $parent_attchment = Attachment::where("attachment_type", 1)->find($parent_id);
            if ($parent_attchment) {
                $parent_path = ltrim($parent_attchment['path'], "/");
            }
        }

        $file_mime = $file->getMime();
        $saveData = [
            'parent_id' => $parent_id,
            'attachment_type' => 2,
            'file_type' => explode("/", $file_mime)[1] ?? 'file',
            'file_name' => $file->getOriginalName(),
            'file_size' => $file->getSize(),
            'mimetype' => $file_mime,
            'disk' => env('filesystem.public', 'public'),
            'sha1' => $file->sha1(),
        ];

        $attachment = Attachment::where('sha1', $saveData['sha1'])->find();
        if (!$attachment){
            $path = $this->putFile($parent_path, $file);
            $saveData['path'] = $path;
            $attachment = Attachment::create($saveData);
        }else{
            // 判断文件是否存在
            if (!file_exists(app()->getRootPath() . 'public' . $attachment['path'])){
                $attachment->delete();
                // 重新上传
                $path = $this->putFile($parent_path, $file);
                $saveData['path'] = $path;
                $attachment = Attachment::create($saveData);
            }
            $path = $attachment['path'];
        }
        return $attachment;
        $username = ZtcUser::where('user_id', $user_id)->value('username');

        if (empty($username)) {
            throw new BusinessException('请先绑定直通车账号');
        }

        $Http_util = Http::invoke();
        $res = $Http_util->request("POST", "http://127.0.0.1:8100/uploadify_visit", [
            'headers' => ['Content-Type' => 'application/json'],
            'body' => json_encode([
                'username' => $username,
                'imgPath' => '..'.str_replace("\\","/",$attachment['path']),
            ])
        ]);
        $res = json_decode($res, 256);
        if ($res['code'] != 1) {

            throw new \Exception($res['msg']);
        }
        return $res['data'];
    }

    public function show($path)
    {
        $url = $this->getRealUrl($path);
        Header("Location: $url");
        exit(0);
    }

    public function putFile($path, $file)
    {
        $root = env('filesystem.root', 'storage');
        $path = Filesystem::putFile($path, $file);
        return "/" . $root . "/". $path;
    }

    public function getRealUrl($path)
    {
        $domain = env('filesystem.host', Request::invoke()->domain());
        $path = "/" . ltrim($path, "/");
        $uri = rtrim($domain, '/');
        return $uri . $path;
    }
}